/*
 * @描述: 机构管理页面逻辑
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import React, { PureComponent, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, TreeSelect, Icon, Button, InputNumber, Modal, message, Divider, Radio, Popconfirm, Tooltip } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { saveAs } from 'file-saver';
import ProTable from '@ant-design/pro-table';

import styles from './Admin.less';

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const InputGroup = Input.Group;
const InputPassword = Input.Password;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, parentOrgData, orgTypeData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  const onChange = value => {
    form.setFieldsValue({
      'parentId': value
    })
  };

  return (
    <Modal
      destroyOnClose
      title={formatMessage({ id: 'app.sysorg.add-org' })}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.sysorg.org-name' })}>
        {form.getFieldDecorator('orgName', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.org-name.required' })
            },
            {
              message: formatMessage({ id: 'validation.org-name.length' }),
              max: 64
            }
          ]
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.sysorg.org-type' })}>
        {form.getFieldDecorator('orgType', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.org-type.required' })
            }
          ]
        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
          {orgTypeData && orgTypeData.map(d => (
            <Option key={d.value}>{d.name}</Option>
          ))}
        </Select>)}
      </FormItem>
      <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.sysorg.org-description' })}>
        {form.getFieldDecorator('orgDescription', {
          rules: [
            {
              message: formatMessage({ id: 'validation.org-description.length' }),
              max: 256
            }
          ]
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.sysorg.org-sequence' })}>
        {form.getFieldDecorator('orgSequence', {

        })(<InputNumber style={{ width: '100%' }} min={1} />)}
      </FormItem>
      <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 15 }}
        label={
          <span>
            <FormattedMessage id="app.sysorg.org-parent" />
            <Tooltip title={<FormattedMessage id="app.common.choose-tooltip" />}>
              <Icon type="info-circle-o" />
            </Tooltip>
          </span>
        }>
        {form.getFieldDecorator('parentId', {

        })(<TreeSelect
          showSearch
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          treeData={parentOrgData}
          placeholder={formatMessage({ id: 'app.common.choose' })}
          treeDefaultExpandAll
          onChange={onChange}
          treeNodeFilterProp="title"
        />)}
      </FormItem>
    </Modal>
  );
});

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => { },
    handleUpdateModalVisible: () => { },
    values: {}
  };

  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        orgName: props.values.orgName,
        orgType: props.values.orgType,
        orgDescription: props.values.orgDescription,
        orgSequence: props.values.orgSequence,
        parentId: props.values.parentId == 0 ? null : props.values.parentId,
        id: props.values.id
      }
    };

    this.formLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 15 }
    };
  }

  renderContent = (formVals) => {
    const { form, parentOrgData, orgTypeData } = this.props;
    const onChange = value => {
      form.setFieldsValue({
        'parentId': value
      })
    };

    return [
      <FormItem key="orgName" {...this.formLayout} label={formatMessage({ id: 'app.sysorg.org-name' })}>
        {form.getFieldDecorator('orgName', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.org-name.required' })
            },
            {
              message: formatMessage({ id: 'validation.org-name.length' }),
              max: 64
            }
          ],
          initialValue: formVals.orgName
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
      <FormItem key="orgType" {...this.formLayout} label={formatMessage({ id: 'app.sysorg.org-type' })}>
        {form.getFieldDecorator('orgType', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.org-type.required' })
            }
          ],
          initialValue: formVals.orgType
        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
          {orgTypeData && orgTypeData.map(d => (
            <Option key={d.value}>{d.name}</Option>
          ))}
        </Select>)}
      </FormItem>,
      <FormItem key="orgDescription" {...this.formLayout} label={formatMessage({ id: 'app.sysorg.org-description' })}>
        {form.getFieldDecorator('orgDescription', {
          rules: [
            {
              message: formatMessage({ id: 'validation.org-description.length' }),
              max: 256
            }
          ],
          initialValue: formVals.orgDescription
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
      <FormItem key="orgSequence" {...this.formLayout} label={formatMessage({ id: 'app.sysorg.org-sequence' })}>
        {form.getFieldDecorator('orgSequence', {
          initialValue: formVals.orgSequence
        })(<InputNumber style={{ width: '100%' }} min={1} />)}
      </FormItem>,
      <FormItem key="parentId" {...this.formLayout}
        label={
          <span>
            <FormattedMessage id="app.sysorg.org-parent" />
            <Tooltip title={<FormattedMessage id="app.common.choose-tooltip" />}>
              <Icon type="info-circle-o" />
            </Tooltip>
          </span>
        }>
        {form.getFieldDecorator('parentId', {
          initialValue: formVals.parentId
        })(<TreeSelect
          showSearch
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          treeData={parentOrgData}
          placeholder={formatMessage({ id: 'app.common.choose' })}
          treeDefaultExpandAll
          onChange={onChange}
          treeNodeFilterProp="title"
        />)}
      </FormItem>
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
    const { formVals } = this.state;
    const okUpdateHandle = () => {
      const { form, handleUpdate } = this.props;
      const { formVals: oldValue } = this.state;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...oldValue, ...fieldsValue };
        this.setState(
          {
            formVals
          },
          () => {
            handleUpdate(formVals);
          }
        );
      });
    };

    return (
      <Modal
        destroyOnClose
        title={formatMessage({ id: 'app.sysorg.edit-org' })}
        visible={updateModalVisible}
        onOk={okUpdateHandle}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
      >
        {this.renderContent(formVals)}
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ sysOrg, loading }) => ({
  sysOrg,
  loading: loading.models.sysOrg,
}))
@Form.create()
class SysOrg extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    parentOrgData: {},
    orgTypeData: {},
    hiddenMenuButton: localStorage.getItem('mscode_menubutton')
  };

  columns = [
    {
      title: formatMessage({ id: 'app.sysorg.org-name' }),
      dataIndex: 'orgName'
    },
    {
      title: formatMessage({ id: 'app.sysorg.org-type' }),
      dataIndex: 'orgTypeCn'
    },
    {
      title: formatMessage({ id: 'app.sysorg.org-description' }),
      copyable: true,
      ellipsis: true,
      dataIndex: 'orgDescription'
    },
    {
      title: formatMessage({ id: 'app.sysorg.org-sequence' }),
      dataIndex: 'orgSequence'
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      render: (text, record) => (
        <Fragment>
          {this.state.hiddenMenuButton.indexOf('sysorg:update') !== -1 ? null :
            <a onClick={() => this.handleUpdateModalVisible(true, record)}><Icon type="edit" />{formatMessage({ id: 'app.common.edit' })}</a>
          }
          <Divider type="vertical" />
          <Popconfirm title={formatMessage({ id: 'app.common.confirm-delete' })} onConfirm={() => this.deleteItem(record.id)}>
            {this.state.hiddenMenuButton.indexOf('sysorg:delete') !== -1 ? null :
              <a><Icon type="delete" />{formatMessage({ id: 'app.common.delete' })}</a>
            }
          </Popconfirm>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysOrg/fetch'
    });
    dispatch({
      type: 'sysOrg/fetchOrgType'
    });
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'sysOrg/fetch',
      payload: params
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {}
    });
    dispatch({
      type: 'sysOrg/fetch',
      payload: {}
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysOrg/delete',
      payload: {
        id: id
      }
    }).then(response => {
      if (response.message == 'success') {
        this.setState({
          selectedRows: []
        });
        message.success(formatMessage({ id: 'app.common.delete-success' }));
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysOrg/fetch',
        payload: {}
      });
    });
  }

  handleDeleteClick = () => {
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) {
      message.warning(formatMessage({ id: 'app.common.choose-delete' }));
      return;
    }

    Modal.confirm({
      title: formatMessage({ id: 'app.common.batch-delete' }),
      content: formatMessage({ id: 'app.common.confirm-batch-delete' }),
      okText: formatMessage({ id: 'app.common.confirm' }),
      cancelText: formatMessage({ id: 'app.common.cancel' }),
      onOk: () => this.deleteItem(selectedRows.map(row => row.id)),
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows
    });
  };

  handleSearch = e => {
    if (e) {
      e.preventDefault();
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue
      };
      this.setState({
        formValues: values
      });
      dispatch({
        type: 'sysOrg/fetch',
        payload: values
      });
    });
  };

  handleExport = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue
      };
      this.setState({
        formValues: values
      });
      dispatch({
        type: 'sysOrg/export',
        payload: values
      }).then(response => {
        saveAs(response, formatMessage({ id: 'app.sysorg.org-manage' }) + '.xlsx');
        dispatch({
          type: 'sysOrg/fetch',
          payload: values
        });
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag
    });
    if (flag == true) {
      const { dispatch } = this.props;
      dispatch({
        type: 'sysOrg/fetchTree'
      });
    }
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {}
    });
    if (flag == true) {
      const { dispatch } = this.props;
      dispatch({
        type: 'sysOrg/fetchTree'
      });
    }
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysOrg/add',
      payload: {
        orgName: fields.orgName,
        orgType: fields.orgType,
        orgDescription: fields.orgDescription,
        orgSequence: fields.orgSequence,
        parentId: fields.parentId ? fields.parentId : 0
      }
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.add-success' }));
        this.handleModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysOrg/fetch',
        payload: {}
      });
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysOrg/update',
      payload: {
        body: {
          orgName: fields.orgName,
          orgType: fields.orgType,
          orgDescription: fields.orgDescription,
          orgSequence: fields.orgSequence,
          parentId: fields.parentId ? fields.parentId : 0,
          id: fields.id
        },
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.edit-success' }));
        this.handleUpdateModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysOrg/fetch',
        payload: {}
      });
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator }, sysOrg: { selectData } } = this.props;
    let orgTypeData;
    if ({ selectData }.selectData) {
      orgTypeData = { selectData }.selectData.list;
    }

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysorg.org-name' })}>
              {getFieldDecorator('orgName')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysorg.org-type' })}>
              {getFieldDecorator('orgType')(
                <Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
                  {orgTypeData && orgTypeData.map(d => (
                    <Option key={d.value}>{d.name}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysorg.org-description' })}>
              {getFieldDecorator('orgDescription')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} type="primary" icon="reload">
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { sysOrg: { data, treeData, selectData }, loading } = this.props;
    const { /**selectedRows,**/ modalVisible, updateModalVisible, updateFormValues } = this.state;
    let parentOrgData;
    let orgTypeData;
    if ({ treeData }.treeData) {
      parentOrgData = { treeData }.treeData.list;
    }
    if ({ selectData }.selectData) {
      orgTypeData = { selectData }.selectData.list;
    }
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate
    };
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.handleSelectRows(selectedRows);
      }
    };
    return (
      <PageHeaderWrapper content={formatMessage({ id: 'app.sysorg.org-manage' })}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              {this.state.hiddenMenuButton.indexOf('sysorg:add') !== -1 ? null :
                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                  {formatMessage({ id: 'app.common.add' })}
                </Button>
              }
              {this.state.hiddenMenuButton.indexOf('sysorg:export') !== -1 ? null :
                <Button icon="file-excel" type="primary" onClick={this.handleExport}>
                  {formatMessage({ id: 'app.common.export' })}
                </Button>
              }
              {this.state.hiddenMenuButton.indexOf('sysorg:delete') !== -1 ? null :
                <Button icon="delete" type="danger" ghost onClick={this.handleDeleteClick}>
                  {formatMessage({ id: 'app.common.batch-delete' })}
                </Button>
              }
            </div>
            <ProTable
              bordered={true}
              search={false}
              rowKey={record => record.id}
              rowSelection={rowSelection}
              loading={loading}
              dataSource={data ? data.list : []}
              pagination={data ? data.pagination : {}}
              columns={this.columns}
              onChange={this.handleBasicTableChange}
              options={{
                density: true,
                reload: () => {
                  this.handleSearch();
                },
                fullScreen: true,
                setting: true,
              }}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} parentOrgData={parentOrgData} orgTypeData={orgTypeData} />
        {updateFormValues && Object.keys(updateFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            parentOrgData={parentOrgData}
            orgTypeData={orgTypeData}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default SysOrg;
